//
//  MoreVC.m
//  APP_login
//
//  Created by edz on 7/6/21.
//  Copyright © 2021 baicai. All rights reserved.
//

#import "PersonalVC.h"
#import "UserSingleton.h"
#import "DatePickerView.h"
#import "GenderView.h"
#import "EditLearnTagVC.h"
#import "InformationVC.h"
#import "TagModel.h"
#import "BZKTools.h"
#import "Masonry.h"


@interface PersonalVC ()
<DatePickerViewDelegate,
SelectGenderDelegate,
UITextFieldDelegate,
UIAlertViewDelegate,
UITabBarControllerDelegate,
EditLearnTagVCDelegate
>
@property (nonatomic, strong) UIButton *saveButton;
@property (nonatomic, strong) UIImageView *imageView;
@property (nonatomic, strong) UILabel *nickNameLable;
@property (nonatomic, strong) UITextField *nickNameTextField;
@property (nonatomic, strong) UILabel *genderTitleLable;
@property (nonatomic, strong) UILabel *genderLable;
@property (nonatomic, strong) UILabel *birthdayTitleLable;
@property (nonatomic, strong) UILabel *birthdayLable;
@property (nonatomic, strong) UILabel *learnTitleLable;
@property (nonatomic, strong) UILabel *learnLable;
@property (nonatomic, strong) UILabel *describeTileLable;
@property (nonatomic, strong) UITextField *describeTextField;
@property (nonatomic, strong) UserSingleton *userModel;
@property (nonatomic, strong) NSMutableArray *tagArrayFromModel;
@property (nonatomic, strong) UIAlertController *alertView;
@property (nonatomic, strong) GenderView * genderView;
@end

@implementation PersonalVC

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.title = @"编辑个人资料";
    self.view.backgroundColor = [UIColor whiteColor];
    
    _userModel = [UserSingleton new];   
    _userModel.model = [InformationModel readData];
    _tagArrayFromModel = [[NSMutableArray alloc] init];
    _tagArrayFromModel = _userModel.model.leranTagArray;
    
    _saveButton = [UIButton buttonWithType:UIButtonTypeSystem];
    [_saveButton mas_makeConstraints:^(MASConstraintMaker *make){
        make.size.mas_equalTo(CGSizeMake(70, 30));
    }];
    [_saveButton setTitle:@"保存" forState:UIControlStateNormal];
    [_saveButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    _saveButton.backgroundColor = [UIColor colorWithRed:239/255 green:241/255 blue:242/255 alpha:0.3];
    _saveButton.enabled = NO;
    [_saveButton.layer setMasksToBounds:YES];
    [_saveButton.layer setCornerRadius:7.0];
    [_saveButton addTarget:self action:@selector(saveInformation) forControlEvents:UIControlEventTouchUpInside];
    
    UIBarButtonItem *leftButton = [[UIBarButtonItem alloc] initWithCustomView:_saveButton];
    self.navigationItem.rightBarButtonItem = leftButton;
    
    _imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"icon"]];
    [self.view addSubview:_imageView];
    [_imageView mas_makeConstraints:^(MASConstraintMaker *make){
        make.left.mas_equalTo(10);
        make.top.mas_equalTo(20);
        make.width.height.mas_equalTo(80);
    }];
    
    _nickNameLable = [[UILabel alloc] init];
    [self.view addSubview:_nickNameLable];
    [_nickNameLable mas_makeConstraints:^(MASConstraintMaker *make){
        make.left.mas_equalTo(10);
        make.top.mas_equalTo(140);
        make.size.mas_equalTo(CGSizeMake(50, 30));
    }];
    _nickNameLable.text = @"昵称";
    _nickNameLable.font = [UIFont systemFontOfSize:18];
    _nickNameLable.textColor = [UIColor grayColor];
    
    _nickNameTextField = [[UITextField alloc] init];
    [self.view addSubview:_nickNameTextField];
    _nickNameTextField.text = _userModel.model.nickName;
    [_nickNameTextField mas_makeConstraints:^(MASConstraintMaker *make){
        make.left.mas_equalTo(90);
        make.top.mas_equalTo(140);
        make.size.mas_equalTo(CGSizeMake(100, 30));
    }];
    _nickNameTextField.keyboardType = UIKeyboardTypeDefault;
    _nickNameTextField.delegate = self;
    
    _genderTitleLable = [[UILabel alloc] init];
    [self.view addSubview:_genderTitleLable];
    _genderTitleLable.text = @"性别";
    [_genderTitleLable mas_makeConstraints:^(MASConstraintMaker *make){
           make.left.mas_equalTo(10);
           make.top.mas_equalTo(200);
           make.size.mas_equalTo(CGSizeMake(50, 30));
       }];
    _genderTitleLable.textColor =[UIColor grayColor];
    _genderTitleLable.font = [UIFont systemFontOfSize:18];
    
    //枚举
    _genderLable = [[UILabel alloc] init];
    [self.view addSubview:_genderLable];
    [_genderLable mas_makeConstraints:^(MASConstraintMaker *make){
        make.left.mas_equalTo(90);
        make.top.mas_equalTo(200);
        make.size.mas_equalTo(CGSizeMake(300, 30));
    }];
    if (_userModel.model.gender == GenderTypeMan) {
        _genderLable.text = @"男";
    }else{
        _genderLable.text = @"女";
    }
    _genderLable.userInteractionEnabled = YES;
    UITapGestureRecognizer *genderLableTag = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(genderLableTag:)];
    [_genderLable addGestureRecognizer:genderLableTag];
    
    UIView *genderBottomBorder = [[UIView alloc] init];
    [self.view addSubview:genderBottomBorder];
    [genderBottomBorder mas_makeConstraints:^(MASConstraintMaker *make){
        make.left.mas_equalTo(10);
        make.right.mas_equalTo(-10);
        make.top.mas_equalTo(244);
        make.height.mas_equalTo(0.3);
    }];
    genderBottomBorder.backgroundColor = [UIColor grayColor];
    

    UIImage  *icon = [UIImage imageNamed:@"rightTriangle"];
    UIImageView *genderIcon = [[UIImageView alloc] initWithImage:icon];
    [self.view addSubview:genderIcon];
    [genderIcon mas_makeConstraints:^(MASConstraintMaker *make){
        make.top.mas_equalTo(206);
        make.right.mas_equalTo(-40);
        make.width.height.mas_equalTo(15);
    }];
    
    
    _birthdayTitleLable = [[UILabel alloc] init];
    [self.view addSubview: _birthdayTitleLable];
    _birthdayTitleLable.text = @"生日";
    [_birthdayTitleLable mas_makeConstraints:^(MASConstraintMaker *make){
        make.left.mas_equalTo(10);
        make.top.mas_equalTo(260);
        make.size.mas_equalTo(CGSizeMake(50, 30));
    }];
    
    _birthdayTitleLable.textColor = [UIColor grayColor];
    
    _birthdayLable = [[UILabel alloc] init];
    [self.view addSubview:_birthdayLable];
    [_birthdayLable mas_makeConstraints:^(MASConstraintMaker *make){
        make.left.mas_equalTo(90);
        make.top.mas_equalTo(260);
        make.size.mas_equalTo(CGSizeMake(300, 30));
    }];
    _birthdayLable.text = _userModel.model.birthday;
    _birthdayLable.userInteractionEnabled = YES;
    UITapGestureRecognizer *birthdayLableTag = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(birthdayLableTag:)];
    [_birthdayLable addGestureRecognizer:birthdayLableTag];
    
    UIView *birthdayBottomBorder = [[UIView alloc] init];
    [self.view addSubview:birthdayBottomBorder];
    [birthdayBottomBorder mas_makeConstraints:^(MASConstraintMaker *make){
        make.left.mas_equalTo(10);
        make.right.mas_equalTo(-10);
        make.top.mas_equalTo(304);
        make.height.mas_equalTo(0.3);
    }];
    birthdayBottomBorder.backgroundColor = [UIColor grayColor];
    
    UIImageView *birthdayIcon = [[UIImageView alloc] initWithImage:icon];
    [self.view addSubview:birthdayIcon];
    [birthdayIcon mas_makeConstraints:^(MASConstraintMaker *make){
        make.top.mas_equalTo(266);
        make.right.mas_equalTo(-40);
        make.width.height.mas_equalTo(15);
    }];
    
    _learnTitleLable = [[UILabel alloc] init];
    [self.view addSubview:_learnTitleLable];
    _learnTitleLable.text = @"学习标签";
    [_learnTitleLable mas_makeConstraints:^(MASConstraintMaker *make){
           make.left.mas_equalTo(10);
           make.top.mas_equalTo(320);
           make.size.mas_equalTo(CGSizeMake(80, 30));
       }];
    
    _learnLable = [[UILabel alloc] init];
    [self.view addSubview:_learnLable];
    if (_userModel.model.leranTagArray.count != 0) {
        _learnLable.text = [self getLearnTagString:_userModel.model.leranTagArray];
    }
    [_learnLable mas_makeConstraints:^(MASConstraintMaker *make){
        make.left.mas_equalTo(90);
        make.top.mas_equalTo(320);
        make.size.mas_equalTo(CGSizeMake(300, 30));
    }];
    _learnLable.font = [UIFont systemFontOfSize:18];
    _learnLable.userInteractionEnabled = YES;
    UITapGestureRecognizer *learnLableTag = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(learnLableTag:)];
    [_learnLable addGestureRecognizer:learnLableTag];
    
    UIImageView *learnIcon = [[UIImageView alloc] initWithImage:icon];
    [self.view addSubview:learnIcon];
    [learnIcon mas_makeConstraints:^(MASConstraintMaker *make){
        make.top.mas_equalTo(320);
        make.right.mas_equalTo(-40);
        make.width.height.mas_equalTo(15);
    }];
    
    _describeTileLable = [[UILabel alloc] init];
    [self.view addSubview:_describeTileLable];
    _describeTileLable.text = @"个人描述";
    [_describeTileLable mas_makeConstraints:^(MASConstraintMaker *make){
        make.left.mas_equalTo(10);
        make.top.mas_equalTo(380);
        make.size.mas_equalTo(CGSizeMake(90, 30));
    }];
    
    _describeTextField = [[UITextField alloc] init];
    [self.view addSubview: _describeTextField];
    _describeTextField.text = _userModel.model.describe;
    [_describeTextField mas_makeConstraints:^(MASConstraintMaker *make){
        make.left.mas_equalTo(10);
        make.top.mas_equalTo(440);
        make.size.mas_equalTo(CGSizeMake(200, 30));
    }];
    _describeTextField.keyboardType = UIKeyboardTypeDefault;
    _describeTextField.delegate = self;
    
    
}

- (void) touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    [self.view endEditing:YES];
}

#pragma mark - 遍历标签数组转为字符串
- (NSString*) getLearnTagString:(NSMutableArray *) array{
    if (array.count != 0) {
        NSMutableString * str = [[NSMutableString alloc] init];
        for (int i = 0; i < array.count; i++) {
            TagModel *model = array[i];
            if (i == array.count-1) {
                [str appendString:model.tagTittle];
            }else{
                [str appendString:[model.tagTittle stringByAppendingString:@"/"]];
            }
        }
        return str;
    }
    return nil;
}
#pragma mark - 性别lable点击手势
- (void) genderLableTag: (UITapGestureRecognizer*) lable{
     _genderView = [[GenderView alloc] init];
    [_genderView showView:[self getKeyWindow]];
    [_genderView mas_makeConstraints:^(MASConstraintMaker *make){
        make.size.mas_equalTo(CGSizeMake(SCREEN_WIDTH, SCREEN_HEIGHT));
    }];
    _genderView.delegate = self;
    _genderView.dataArray = @[@"男",@"女"];
}

#pragma mark -自定义性别选择器代理
- (void) genderViewWillRemove:(NSInteger)row{
    if (row == 0) {
        _genderLable.text = @"男";
    }
    if (row == 1) {
        _genderLable.text = @"女";
    }
    [self checkInformationIsChanged];
}
#pragma mark -时间lable点击手势
- (void) birthdayLableTag: (UITapGestureRecognizer*) lable{
    DatePickerView *picker = [[DatePickerView alloc] init];
    [picker showView:[self getKeyWindow]];
    [picker mas_updateConstraints:^(MASConstraintMaker *make){
        make.size.mas_equalTo(CGSizeMake(SCREEN_WIDTH, SCREEN_HEIGHT));
    }];
    picker.delegate = self;
}

#pragma mark -自定义时间选择器代理
- (void) datePickerViewSetBirthdayData:(NSString *)data{
    if (data != nil) {
        _birthdayLable.text = data;
        [self checkInformationIsChanged];
    }
}

#pragma mark -学习标签点击手势
- (void) learnLableTag: (UITapGestureRecognizer*) lable{
    EditLearnTagVC * editLearnVc = [[EditLearnTagVC alloc] init];
    editLearnVc.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:editLearnVc animated:YES];
    editLearnVc.delegate = (id)self;
    editLearnVc.oldArray = _tagArrayFromModel;
}

#pragma mark -学习标签代理

- (void) editLearnTagVCSetNewTagArray:(NSMutableArray*)tagArray{
    _tagArrayFromModel = tagArray;
    NSString *string = [self getLearnTagString:tagArray];
    _learnLable.text = string;
    [self checkInformationIsChanged];
}

- (BOOL) checkModel{
    if (_tagArrayFromModel.count == _userModel.model.leranTagArray.count) {
        for (int i = 0; i<_tagArrayFromModel.count; i++) {
            TagModel *model1 = _tagArrayFromModel[i];
            NSInteger count = 0;
            for (int j = 0; j<_userModel.model.leranTagArray.count; j++) {
                 TagModel *model2 = _userModel.model.leranTagArray[i];
                 if (![model1.tagTittle isEqualToString:model2.tagTittle]) {
                     count++;
                 }
            }
            if (count == _tagArrayFromModel.count) {
                return NO;
            }else{
                count = 0;
            }
        }
    }else{
        return NO;
    }
    return YES;
}

#pragma mark -内容改变监听
- (void) textFieldDidChangeSelection:(UITextField *)textField{
    [self checkInformationIsChanged];
}
//判断改变后的值是否相同
- (BOOL) checkInformationIsChanged{
    if ([_nickNameTextField.text isEqualToString: _userModel.model.nickName] &
        [_describeTextField.text isEqualToString:_userModel.model.describe] &
        [_birthdayLable.text isEqualToString: _userModel.model.birthday]&
        [self checkGender] & [self checkModel]
        ){
        _saveButton.enabled = NO;
        _saveButton.backgroundColor = [UIColor colorWithRed:239/255 green:241/255 blue:242/255 alpha:0.3];
        return NO;
    }else{
        _saveButton.enabled = YES;
        _saveButton.backgroundColor = [UIColor blueColor];
        return YES;
    }
    
}

- (BOOL) checkGender{
    if ([_genderLable.text isEqualToString: @"男"]) {
        if (_userModel.model.gender == GenderTypeMan) {
            return YES;
        }else{
            return NO;
        }
    }else{
        if (_userModel.model.gender == GenderTypeFemale) {
            return YES;
        }else{
            return NO;
        }
    }
}

- (void) saveInformation{
    _userModel.model.nickName = _nickNameTextField.text;
    _userModel.model.birthday = _birthdayLable.text;
    if ([_genderLable.text isEqualToString: @"男"]) {
        _userModel.model.gender = GenderTypeMan;
    }else{
        _userModel.model.gender = GenderTypeFemale;
    }
    _userModel.model.leranTagArray = _tagArrayFromModel;
    _userModel.model.describe = _describeTextField.text;
    [_userModel.model writeData];
    UIAlertController *alertView = [UIAlertController alertControllerWithTitle:@"提示" message:@"保存成功" preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *action = [UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action){
            self.saveButton.enabled = NO;
            self.saveButton.backgroundColor = [UIColor colorWithRed:239/255 green:241/255 blue:242/255 alpha:0.3];
       }];
    [alertView addAction:action];
    [self presentViewController:alertView animated:YES completion:nil];
}

- (void) cancelSaveInformation{
//    _nickNameTextField.text = _nickNameFromModel;
//    _birthdayLable.text = _birthdayFromModel;
//    if (_gendereFromModel == GenderTypeMan) {
//        _genderLable.text = @"男";
//    }else{
//        _genderLable.text = @"女";
//    }
//    _learnLable.text = [self getLearnTagString:_tagArrayFromModel];
//    _describeTextField.text = _describeFromModel;
}

- (void) initAlertView{
//    _alertView = [UIAlertController alertControllerWithTitle:@"确认返回吗？" message:@"当前资料修改尚未保存，返回后所有修改将不会生效" preferredStyle:UIAlertControllerStyleAlert];
//    UIAlertAction *action = [UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action){
//        [self cancelSaveInformation];
//    }];
//    UIAlertAction *action1 = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action){
//        [self saveInformation];
//    }];
//    [_alertView addAction:action];
//    [_alertView addAction:action1];
//    [self presentViewController:_alertView animated:YES completion:nil];
}

#pragma mark -工具
- (UIImage *) scaleToSize:(UIImage *)img size:(CGSize)size {
     // 创建一个bitmap的context
     // 并把它设置成为当前正在使用的context
     UIGraphicsBeginImageContext(size);
     // 绘制改变大小的图片
     [img drawInRect:CGRectMake(0, 0, size.width, size.height)];
     // 从当前context中创建一个改变大小后的图片
     UIImage* scaledImage = UIGraphicsGetImageFromCurrentImageContext();
     // 使当前的context出堆栈
     UIGraphicsEndImageContext();
     // 返回新的改变大小后的图片
     return scaledImage;
}
- (UIWindow*)getKeyWindow{
    for (UIWindow *window in [[UIApplication sharedApplication] windows]) {
        if (window.isKeyWindow) {
            return window;
        }
    }
    return nil;
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
